from datetime import datetime, timedelta
import time
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News
from info.utils.commons import login_required
from info.utils.response_code import RET
from . import admin_blue




@admin_blue.route('/index')
@login_required
def index():
    """后台管理首页"""

    user = g.user
    return render_template('admin/index.html',user=user.to_dict())

#后台登录页
@admin_blue.route('/login',methods=["GET","POST"])
@login_required
def login():
    user = g.user

    if request.method == "GET":
        #判断是否已经登录，如果已经登录直接到后台页面
        user_id =session.get("user_id",None)
        is_admin = session.get("is_admin",False)
        if user_id and is_admin:
            return redirect(url_for("admin.index"))
        return render_template("admin/login.html")

    user_name = request.form.get("username")
    password = request.form.get("password")
    if not all([user_name,password]):
        return render_template("admin/login.html",errmsg="参数不完整")
    try:
        user = User.query.filter(User.mobile == user_name,User.is_admin==True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html",errmsg="数据库查询错误")
    if user is None or not user.check_password(password):
        return render_template("admin/login.html",errmsg="用户名或密码错误")

    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin
    return redirect(url_for("admin.index"))

#用户统计
@admin_blue.route("/user_count")
@login_required
def user_count():
    #总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询总人数失败")
    #月新增
    mon_count=0
    t = time.localtime()
    mon_begin_date_str = "%d-%02d-01"%(t.tm_year,t.tm_mon)
    #用strptime要把日期字符串转成日期对象
    mon_begin_date = datetime.strptime(mon_begin_date_str,"%Y-%m-%d")
    print(mon_begin_date)

    try:
        mon_count = User.query.filter(User.is_admin == False,User.create_time>mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询月增人数失败")


    #日新增
    day_count = 0
    day_begin_date_str = "%d-%02d-%d"%(t.tm_year,t.tm_mon,t.tm_mday)
    day_begin_date = datetime.strptime(day_begin_date_str,"%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin==False,User.create_time>day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询日增人数失败")
    # 用户活跃度统计
    today_begin_date_str = "%d-%02d-%d"%(t.tm_year,t.tm_mon,t.tm_mday)
    today_begin_date = datetime.strptime(today_begin_date_str,"%Y-%m-%d")
    active_count = []
    active_time = []
    for d in range(0,30):
        begin_date =today_begin_date - timedelta(days=d)
        end_date = today_begin_date - timedelta(days=(d - 1))
        try:
            count = User.query.filter(User.is_admin==False,User.last_login>=begin_date,User.last_login<end_date).count()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(error=RET.DBERR,errmsg="查询活跃用户失败")

        active_count.append(count)
        begin_date_str = datetime.strftime(begin_date,"%Y-%m-%d")

        active_time.append(begin_date_str)
        # print(active_time)
        # print(active_count)
    active_time.reverse()
    active_count.reverse()


    data={
        "total_count":total_count,
        "mon_count":mon_count,
        "day_count":day_count,
        "active_time":active_time,
        "active_count":active_count
    }
    return render_template("admin/user_count.html",data=data)

@admin_blue.route("/user_list")
def user_list():
    #
    page = request.args.get("p",1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    users = []
    current_page = 1
    total_page = 1

    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        users = paginate.items #获取分页后的数据
        current_page = paginate.page #查看当前页
        total_page = paginate.pages #总共多少页
    except Exception as e:
        current_app.logger.error(e)

    users_list = []

    for user in users:
        users_list.append(user.to_admin_dict())
    # print(users_list)
    data = {"total_page":total_page,"current_page":current_page,"users":users_list}
    return render_template("admin/user_list.html",data=data)



#新闻模块，个人中心，后台，通行模块（登录注册）


#新闻审核
@admin_blue.route("/news_review")
@login_required
def news_review():
    page = request.args.get("p",1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        return jsonify(error=RET.PARAMERR, errmsg="数据格式错误")


    news_list = []
    current_page =1
    total_page =1
    try:
        paginate = News.query.filter(News.status != 0).order_by(News.create_time.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="查询错误")


    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())
    print(news_dict_list)
    data = {
        "total_page":total_page,"current_page":current_page,"news_list":news_dict_list
    }
    return render_template("admin/news_review.html",data=data)


#新闻审核详情
@admin_blue.route("/news_review_detail",methods =["GET","POST"])
def news_review_detail():
    if request.method == "GET":

        # 获取新闻id
        news_id = request.args.get("news_id")
        if not news_id:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        # 通过id查询新闻
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)


        if not news:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        # 返回数据
        data = {"news": news.to_dict(),
                "errmsg": "审核失败"
                }
        return render_template('admin/news_review_detail.html', data=data)



    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # content = request.form,subajax

    if not all([news_id,action]):
        return jsonify(error=RET.PARAMERR,errmsg="参数错误")
    if action not in("accept","reject"):
        return jsonify(error=RET.PARAMERR,errmsg="参错误")

    news =None

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="查询错误")

    if not news:
        return jsonify(error=RET.PARAMERR, errmsg="w为查询数据")
    if action == "accept":
        print(action,action == "accept")
        news.status = 0
    else:
        reason = request.json.get("reason")
        if not reason:
            return jsonify(error=RET.PARAMERR, errmsg="参数错误")
        news.reason= reason
        news.status = -1

        # print(action,news_id)
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(error=RET.DBERR,errmsg="数据保存失败")
    return jsonify(error=RET.OK, errmsg="操作成功")




